package com.prb.framework.servlet;

import com.prb.framework.factory.AnnotationBeanFactory;
import com.prb.framework.invoke.HandlerMethod;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

public class PrbDispatchService extends HttpServlet {


    public Set<String> excludeRes = new HashSet();

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {

        excludeRes.add(".jsp");
        excludeRes.add(".html");
        excludeRes.add(".css");
        excludeRes.add(".ico");
//com.prb
        String scannerPackage = servletConfig.getInitParameter("scannerPackage");

        try {
            doScanner(scannerPackage);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String requestURI = req.getRequestURI();

        //静态资源不做处理
        for (String excludeRe : excludeRes) {
            if(requestURI.endsWith(excludeRe)){
                return ;
            }
        }

        HandlerMethod hm = getHandlerMapping(requestURI);
        if(hm == null){

            resp.getWriter().write("404");
            resp.flushBuffer();
            return ;
        }

        System.out.println(requestURI);

        try {
            preInvoke(req , resp , hm);
            Object invoke = hm.invoke();
            resp.getWriter().write(invoke.toString());

        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

    }

    private void preInvoke(HttpServletRequest req , HttpServletResponse resp , HandlerMethod hm) {

        Map<String, Integer> param = hm.getParam();

        Method method = hm.getMethod();

        Class<?>[] parameterTypes = method.getParameterTypes();

        Object[] args = new Object[parameterTypes.length];

        Map<String, String[]> parameterMap = req.getParameterMap();

        for (Map.Entry<String, Integer> entry : param.entrySet()) {
            String join = "";
            String[] strings = parameterMap.get(entry.getKey());
            if(strings != null){
                join = StringUtils.join(strings , ",");
            }
            args[entry.getValue()] = join;
        }

        Integer reqIndex = param.get(HttpServletRequest.class.getSimpleName());
        Integer respIndex = param.get(HttpServletResponse.class.getSimpleName());

        args[reqIndex] = req;
        args[respIndex] = resp;

        hm.setArgs(args);

    }

    private HandlerMethod getHandlerMapping(String requestURI) {

        for (HandlerMethod handlerMethod : AnnotationBeanFactory.handlerMethodList) {
            if(handlerMethod.getReqPath().equals(requestURI)){
                return handlerMethod;
            }
        }
        return null;
    }

    @Override
    public String getServletInfo() {
        return null;
    }

    @Override
    public void destroy() {

    }




    private void doScanner(String scannerPackage) throws ClassNotFoundException, InvocationTargetException, InstantiationException, IllegalAccessException {

        AnnotationBeanFactory.doScan(scannerPackage);

    }
}
